import React, {Component} from 'react'
import {SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity, TouchableHighlight,
    ScrollView,
    Modal, StyleSheet, Platform, BackHandler, ToastAndroid} from 'react-native'
import CodePush from "react-native-code-push"
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../constant/PHScreen";
import global from "../../configuration/global";

let codePushOptions = {
    checkFrequency : CodePush.CheckFrequency.ON_APP_START
}

class CodePushView extends Component {

    constructor(props) {
        super(props)
        this.syncMessage = '';
        this.state = {
            modalVisible: false,
            isMandatory: false,
            immediateUpdate: false,
            updateInfo: {}
        }
    }

    codePushStatusDidChange(syncStatus) {
        if (this.state.immediateUpdate) {
            switch(syncStatus) {
                case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
                    this.syncMessage = 'Checking for update'
                    break;
                case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
                    this.syncMessage = 'Downloading package'
                    break;
                case CodePush.SyncStatus.AWAITING_USER_ACTION:
                    this.syncMessage = 'Awaiting user action'
                    break;
                case CodePush.SyncStatus.INSTALLING_UPDATE:
                    this.syncMessage = 'Installing update'
                    break;
                case CodePush.SyncStatus.UP_TO_DATE:
                    this.syncMessage = 'App up to date.'
                    break;
                case CodePush.SyncStatus.UPDATE_IGNORED:
                    this.syncMessage = 'Update cancelled by user'
                    break;
                case CodePush.SyncStatus.UPDATE_INSTALLED:
                    this.syncMessage = 'Update installed and will be applied on restart.'
                    break;
                case CodePush.SyncStatus.UNKNOWN_ERROR:
                    this.syncMessage = 'An unknown error occurred'
                    // ToastAndroid.show('更新出错，请重启应用！',1000)
                    this.setState({modalVisible: false})
                    break;
            }
        }
    }

    syncImmediate() {
        CodePush.checkForUpdate(global.CODE_PUSH_KEY).then((update) => {
            console.log('-------' + update)
            if (!update) {
                ToastAndroid.show('已是最新版本！',1000)
            } else {
                this.setState({modalVisible: true, updateInfo: update, isMandatory: update.isMandatory})
            }
        })
    }

    componentWillMount() {
        CodePush.disallowRestart()
        this.syncImmediate()
    }

    componentDidMount() {
        CodePush.allowRestart()
    }

    _immediateUpdate() {
        this.setState({immediateUpdate: true})
        CodePush.sync(
            {deploymentKey: global.CODE_PUSH_KEY, updateDialog: {}, installMode: CodePush.InstallMode.IMMEDIATE},
            this.codePushStatusDidChange.bind(this),
        )
    }

    renderModal() {
        return (
            <Modal
                animationType={"none"}
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => alert("Modal has been closed.")}>
                <View style={styles.modal}>
                    <View style={styles.modalContainer}>
                        {
                            !this.state.immediateUpdate ?
                                <View>
                                    <View style={{backgroundColor: 'white'}}>
                                        <View style={{marginHorizontal: 15}}>
                                            <Text style={{marginVertical: 20, fontSize: 17, color: 'gray', fontWeight: 'bold'}}>更新内容</Text>
                                            <Text style={{lineHeight: 20}}>{this.state.updateInfo.description}</Text>
                                        </View>
                                        <View style={{alignItems: 'center', marginTop: 20}}>
                                            <Text style={{fontSize: 14, color: 'gray'}}>wifi情况下更新不到30秒</Text>
                                        </View>
                                        {
                                            !this.state.isMandatory ?
                                                <View style={{flexDirection: 'row', height: 50, alignItems: 'center', marginTop: 20, borderTopColor: '#ccc', borderTopWidth: 1 }}>
                                                    <TouchableOpacity
                                                        onPress={() => this.setState({modalVisible: false})}>
                                                        <View style={{flexDirection: 'row', alignItems: 'center', width: (SCREEN_WIDTH - 60) / 2, height: 50, borderRightColor: '#ccc', borderRightWidth: 1, alignItems: 'center', justifyContent: 'center'}}>
                                                            <Text style={{fontSize: 17, fontWeight: 'bold', color: 'gray', marginLeft: 10}}>残忍拒绝</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity
                                                        style={{flexDirection: 'row', alignItems: 'center', width: (SCREEN_WIDTH - 60) / 2, height: 50, alignItems: 'center', justifyContent: 'center'}}
                                                        onPress={() => this._immediateUpdate()}
                                                    >
                                                        <View style={{backgroundColor: '#3496FA', flex: 1, height: 40, alignItems: 'center', justifyContent: 'center', margin: 10, borderRadius: 20}}>
                                                            <Text style={{fontSize: 17, color: 'white', fontWeight: 'bold'}}>极速下载</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                </View> :
                                                <View style={{flexDirection: 'row', height: 60, alignItems: 'center', marginTop: 20, borderTopColor: '#ccc', borderTopWidth: 1, width: SCREEN_WIDTH - 60}}>
                                                    <TouchableOpacity
                                                        style={{flexDirection: 'row', alignItems: 'center', width: (SCREEN_WIDTH - 60), height: 50, alignItems: 'center', justifyContent: 'center'}}
                                                        onPress={() => this._immediateUpdate()}
                                                    >
                                                        <View style={{backgroundColor: '#3496FA', flex: 1, height: 40, alignItems: 'center', justifyContent: 'center', borderRadius: 20, marginHorizontal: 40}}>
                                                            <Text style={{fontSize: 17, color: 'white', fontWeight: 'bold'}}>立即更新</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                </View>
                                        }
                                    </View>
                                </View> :
                                <View>
                                    <View style={{backgroundColor: 'white', paddingVertical: 20, backgroundColor: 'white', alignItems: 'center'}}>
                                        <View style={{alignItems: 'center', marginVertical: 20}}>
                                            <Text style={{fontSize: 14, color: 'gray'}}>版本正在努力更新中，请等待</Text>
                                        </View>
                                    </View>
                                </View>
                        }
                    </View>
                </View>
            </Modal>
        )
    }

    render(){
        return(
            <View style={styles.container}>
                {this.renderModal()}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white'
    },
    modal: {
        height: SCREEN_HEIGHT,
        width: SCREEN_WIDTH,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgba(0,0,0,0.3)'
    },
    modalContainer: {
        marginHorizontal: 60,
        borderBottomLeftRadius: 10,
        borderBottomRightRadius: 10,
    }
})

export default CodePush(codePushOptions)(CodePushView)